// 专门为reducer生成action对象
import { CREATE_SIP, SET_SIP_CALL_TIME, SET_SIP_MESSAGE, SET_SIP_VISIBLE_OPERATION } from "./constant";
import { Dispatch } from "react";
import SipCall from "../../utils/sipCall";
import { CallEndEvent, LatencyStat, SipConfig, StateListenerMessage } from "../../types";
import TimerCall from "../../utils/timerCall";
import { message } from "antd";

const timer = new TimerCall();

// 创建sip实例
export const createSip = (dispatch: Dispatch<{
  type: string,
  data: any
}>, callback: (value: SipCall) => void, options: SipConfig) => {
  let sipClient: SipCall;
  let stateEventListener = (event: string, data: StateListenerMessage | CallEndEvent | LatencyStat | string | null) => {
    if (options.stateEventListener) {
      options.stateEventListener(event, data);
    }

    dispatch(setSipMessage({
      event,
      data
    }));

    if (["OUTGOING_CALL", "IN_CALL"].includes(event)) {
      // 呼出和接通后开始计时
      timer.startTimerCall((value) => {
        dispatch(setSipTime(value));
      });
    }

    if ("CALL_END" === event) {
      // 结束通话
      timer.stopTimerCall((value) => {
        dispatch(setSipTime(value));
      });
    }

    // console.log(event, 'event', data)
    if (event === "REGISTERED") {
      //注册成功
      callback(sipClient);
    }

    // 麦克风错误
    if (event === "MIC_ERROR") {
      if (typeof data === "object" && data !== null && "msg" in data) {
        message.error(data.msg).then(r => r);
      } else {
        message.error("麦克风错误").then(r => r);
      }
    }

  };
  //设置配置信息
  let config: any = {
    proto: true,
    autoRegister: true,
    debug: false,
    stun: {
      type: "stun",
      host: "stun.l.google.com:19302"
    },
    register_expires: 100000000,
    ...(options || {}),
    stateEventListener: stateEventListener
  };
  sipClient = new SipCall(config);

  /*sipClient.ua.on('newMessage', (data) => {
     console.log(data,'newMessage')
   })*/

  dispatch({ type: CREATE_SIP, data: sipClient });
};


//设置sip信息
export const setSipMessage = (data: {
  event: string,
  data: StateListenerMessage | CallEndEvent | LatencyStat | string | null
}) => ({
  type: SET_SIP_MESSAGE,
  data
});


//设置sip呼叫时间
export const setSipTime = (data: string) => ({
  type: SET_SIP_CALL_TIME,
  data
});


export const setSipVisibleOperation = (data: boolean) => ({
  type: SET_SIP_VISIBLE_OPERATION,
  data
});
